package com.huiyeji.crypt;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class _R_2_3_Coder {

    public static String encode(String text){
        return new String(R3Coder.instance.encode(R2Coder.instance_1.encode(text.getBytes())));
    }

    public static byte[] encode(byte[] bytes){
        return R3Coder.instance.encode(R2Coder.instance_1.encode(bytes));
    }

    public static String decode(String text){
        return new String(R2Coder.instance_1.decode(R3Coder.instance.decode(text.getBytes())));
    }

    public static byte[] decode(byte[] bytes){
        return R2Coder.instance_1.decode(R3Coder.instance.decode(bytes));
    }

    public static void encodeFile(String filePath) throws IOException {
        codeFile(filePath,true);
    }

    public static void decodeFile(String filePath) throws IOException {
        codeFile(filePath,false);
    }

    private static void codeFile(String filePath,boolean isEncode) throws IOException {
        Path path = Paths.get(filePath);
        BufferedInputStream bio = null;
        ByteArrayOutputStream buffer = null;
        BufferedOutputStream bo = null;
        try {
            bio = new BufferedInputStream(Files.newInputStream(path));
            buffer = new ByteArrayOutputStream();
            int nRead;
            byte[] data = new byte[16384];
            while ((nRead = bio.read(data, 0, data.length)) != -1) {
                buffer.write(data, 0, nRead);
            }
            byte[] encodeArray = isEncode ? encode(buffer.toByteArray()) : decode(buffer.toByteArray());
            bo = new BufferedOutputStream(Files.newOutputStream(path));
            bo.write(encodeArray);
            bo.flush();
        } catch (Exception exception){
            exception.printStackTrace();
        } finally {
            if (bio != null){
                bio.close();
            }

            if (buffer != null){
                buffer.close();
            }

            if (bo != null){
                bo.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        decodeFile("C:/Users/HW/Desktop/plugins/dashboard.hsp.dy.plugin");
    }
}
